package com.xiaoniu.tcp.client;

import com.xiaoniu.MsgUtils;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Vertx;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.core.net.NetClient;
import io.vertx.core.net.NetClientOptions;
import io.vertx.core.net.NetSocket;
import io.vertx.core.parsetools.RecordParser;


/**
 * Created by sweet on 2018/1/2.
 * ---------------------------
 */
public class TcpClientVerticle extends AbstractVerticle {

    private final Logger LOGGER = LoggerFactory.getLogger(TcpClientVerticle.class);

    public static void main(String[] args) {
        System.setProperty("vertx.logger-delegate-factory-class-name",
                "io.vertx.core.logging.Log4j2LogDelegateFactory");
        Vertx.vertx().deployVerticle(new TcpClientVerticle());
    }

    private String socketId;

    private NetSocket netSocket;

    @Override
    public void start() throws Exception {
        NetClientOptions options = new NetClientOptions();
        options.setTcpKeepAlive(true);

        NetClient client = vertx.createNetClient();

        final RecordParser parser = RecordParser.newDelimited("\n", h -> {
            String msg = h.toString();
            LOGGER.debug("客户端解包: " + msg);
            String[] msgSplit = msg.split("\\*");

            String socketId1 = msgSplit[0];
            String body = msgSplit[1];

            if ("Server".equals(body)) {
                socketId = socketId1;
            }
        });

        client.connect(8080, "127.0.0.1", conn -> {
            if (conn.succeeded()) {
                System.out.println("client ok");
                netSocket = conn.result();
                netSocket.handler(parser::handle);
            } else {
                conn.cause().printStackTrace();
            }
        });

        // 客户端每 20 秒 发送一次心跳包
        vertx.setPeriodic(1000l * 20, t -> {
            if (netSocket != null)
                netSocket.write(MsgUtils.joinMsg(socketId, "PING"));
        });

        // 模拟客户端发消息 每个10秒钟
        vertx.setPeriodic(1000l * 10, t -> {
           if (netSocket != null) {
               netSocket.write(MsgUtils.joinMsg(socketId, "Hello Vert.x"));
           }
        });
//        vertx.setPeriodic(1000l * 4, t -> {
//            if (netSocket != null) {
//                netSocket.write(socketId+"*first");
//                vertx.setTimer(3000l, t1 -> netSocket.write("-helloworld\n"));
//            }
//        });
    }
}
